package org.dyndns.opendemogroup.optimizer;

import java.util.ArrayList;
import java.util.List;

/**
 * Convenience class for raising events. I miss .NET's event mechanism :(
 */
public class OptimizationEventSink
{

	private final OptimizationEvent e;

	private final List<OptimizationListener> listeners =
		new ArrayList<OptimizationListener> ( );

	public OptimizationEventSink ( GenericGenerationalGeneticAlgorithm source )
	{
		e = new OptimizationEvent ( source );
	}

	void finishFitnessComputations ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.finishFitnessComputations ( e );
		}
	}

	void finishGeneration ( Member bestMember )
	{
		e.setBestMember ( bestMember );
		for ( OptimizationListener listener : listeners )
		{
			listener.finishGeneration ( e );
		}
	}

	void finishOperations ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.finishOperations ( e );
		}
	}

	void finishPopulationSort ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.finishPopulationSort ( e );
		}
	}

	void finishRun ( RunResult result )
	{
		e.setRunResult ( result );
		for ( OptimizationListener listener : listeners )
		{
			listener.finishRun ( e );
		}
	}

	void performFitnessComputation ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.performFitnessComputation ( e );
		}
	}

	void performOperation ( int populationIndex )
	{
		e.setPopulationIndex ( populationIndex );
		for ( OptimizationListener listener : listeners )
		{
			listener.performOperation ( e );
		}
	}

	void startFitnessComputations ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.startFitnessComputations ( e );
		}
	}

	void startGeneration ( int gen )
	{
		e.setGen ( gen );
		for ( OptimizationListener listener : listeners )
		{
			listener.startGeneration ( e );
		}
	}

	void startOperations ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.startOperations ( e );
		}
	}

	void startPopulationSort ( )
	{
		for ( OptimizationListener listener : listeners )
		{
			listener.startPopulationSort ( e );
		}
	}

	void startRun ( int run )
	{
		e.setRun ( run );
		for ( OptimizationListener listener : listeners )
		{
			listener.startRun ( e );
		}
	}

	public void addListener ( OptimizationListener listener )
	{
		listeners.add ( listener );
	}

	public void removeListener ( OptimizationListener listener )
	{
		listeners.remove ( listener );
	}
}
